package jianzhiOffer;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

//剑指 Offer 32 - II. 从上到下打印二叉树 II
public class Num32_II_levelOrder {
    public List<List<Integer>> levelOrder(TreeNode root) {
        //存储层序遍历的结果
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null){
            return ret;
        }
        //存储每一层节点
        Deque<TreeNode> queue = new LinkedList<>();
        //存入根节点
        queue.offer(root);
        while (!queue.isEmpty()){
            //存储每一层元素
            List<Integer> cur = new ArrayList<>();
            int size = queue.size();
            //元素不断poll
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                cur.add(node.val);
                if (node.left!=null){
                    queue.offer(node.left);
                }
                if (node.right!=null){
                    queue.offer(node.right);
                }
            }
            ret.add(cur);
        }
        return ret;
    }
}
